package com.tarena.lbs.coupon.config;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class CustomIntegerConverter implements Converter<Integer> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 将 Excel 数据转换为 Java 数据
     */
    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        String stringValue = cellData.getStringValue();
        if (stringValue == null || stringValue.trim().isEmpty()) {
            return null;
        }

        try {
            // 移除可能的前后空格
            String cleanedValue = stringValue.trim();

            // 处理特殊字符
            if ("通".equals(cleanedValue)) {
                return 1; // 根据业务需求返回合适的值
            }

            // 尝试转换为整数
            return Integer.parseInt(cleanedValue);
        } catch (NumberFormatException e) {
            log.warn("无法将字符串 '{}' 转换为整数，返回默认值 0", stringValue);
            return 0; // 或者返回 null，根据业务需求
        }
    }

    /**
     * 将 Java 数据转换为 Excel 数据
     */
    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData<>("");
        }
        return new WriteCellData<>(value.toString());
    }
}